import React, {Component} from 'react'
import {
    View,
    Dimensions,
    LayoutAnimation,
    UIManager,
    Platform,
    Modal,
    Text,
    StyleSheet,
    TouchableOpacity, ActivityIndicator
} from 'react-native'
import IparInput from "../custom/IparInput";
import StyleUtils from "../res/styles/StyleUtils";
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view'
import IparNetwork, {SERVER_TYPE} from "../httpUtils/IparNetwork";
import I18n from "../res/language/i18n";

let {width, height} = Dimensions.get('window');

export default class RegisterRecommenderAlert extends Component {

    constructor(props) {
        super(props);
        this.state = {
            marginRight: 0,
            loading: false,
            errorText: null,
        };

        this.iparNetwork = new IparNetwork();
        this.recommenderNumber = '';
    }

    /**
     * 动画效果
     */
    startAnimation() {
        if (Platform.OS === 'android') {
            UIManager.setLayoutAnimationEnabledExperimental(true);
        }
        LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
    }

    startErrorAnim(errorText) {
        this.setState({
            marginRight: 60,
            errorText,
        });
        setTimeout(() => {
            this.setState({
                marginRight: 0
            });
        }, 10);
    }

    componentWillUpdate() {
        this.startAnimation();
    }

    checkUser() {
        let sponserId = this.recommenderNumber;
        if (!sponserId) {
            this.startErrorAnim(I18n.t('default.sponsorId'));
            return;
        }
        let inde = sponserId.indexOf('.');
        if (inde <= 0) {
            this.startErrorAnim(I18n.t('default.noReferee'));
            return;
        }
        let userInfo = this.props.userInfo;

        let rank = sponserId.substring(inde + 1, inde + 2);
        this.setState({
            errorText: null,
            loading: true,
        });
        this.iparNetwork.getRequest(SERVER_TYPE.admin + 'searchSponsor?', "keywords=" + sponserId + '&rank=' + rank)
            .then((res) => {
                console.log(res);
                let errorText = null;
                let loading = false;
                if (res.code === 200) {
                    let sponsorUserInfo = res.data;
                    loading = true;
                    this.openSubAcount(userInfo, sponsorUserInfo, rank, sponserId);
                } else {
                    errorText = I18n.t('default.noReferee')
                }
                this.setState({
                    errorText,
                    loading,
                });
            })
            .catch((err) => {
                console.log('error----' + err);
                this.setState({
                    errorText: I18n.t('default.fail'),
                    loading: false,
                });
            })
    }


    /**
     * 开子账号
     */
    openSubAcount(userInfo, sponsorUserInfo, rank, sponsorId) {
        // if (!userInfo ) {
        //     this.setState({
        //         errorText: I18n.t('default.fail'),
        //         loading: false,
        //     });
        //     return;
        // }
        // if (!sponsorUserInfo ) {
        //     this.setState({
        //         errorText: I18n.t('default.fail'),
        //         loading: false,
        //     });
        //     return;
        // }

        console.log(userInfo);
        let formData = new FormData();
        formData.append("main_user_id", userInfo.main_user_id);
        formData.append("rank", rank);
        formData.append("keywords", sponsorId);
        formData.append("code", sponsorUserInfo.code);
        formData.append("country", userInfo.country);
        formData.append('froms', Platform.OS === 'ios' ? 'IOS' : 'Android');
        formData.append("sponsor", sponsorId);
        this.iparNetwork.getPostFrom(SERVER_TYPE.admin + 'openSubAccount', formData)
            .then((res) => {
                console.log(res);
                if (res.code === 200) {
                    this.props.requestClose && this.props.requestClose();
                    this.props.success && this.props.success();
                } else {
                    this.setState({
                        errorText: I18n.t('default.fail'),
                        loading: false,
                    });
                }
            })
            .catch((err) => {
                console.log('error---' + err);
                this.setState({
                    errorText: I18n.t('default.fail'),
                    loading: false,
                });
            })
    }


    render() {
        const {marginRight, errorText, loading} = this.state;
        const {requestClose, visible} = this.props;

        return (
            <Modal
                animationType='fade'
                transparent={true}
                visible={visible}
                onRequestClose={requestClose}
            >
                <KeyboardAwareScrollView style={{backgroundColor: 'rgba(0,0,0,0.5)',}}>
                    <View style={styles.box}>
                        <View style={[styles.alert, {marginRight}]}>
                            <Text style={styles.title}>{I18n.t('alert.whoToldYouAboutIPAR')}</Text>
                            <Text>{I18n.t('alert.referingMemberr')}</Text>

                            <IparInput
                                editable={!loading}
                                autoFocus={true}
                                style={{height: 36, borderRadius: 4, marginTop: 28}}
                                numberOfLines={1}
                                onChangeText={(text) => {
                                    this.recommenderNumber = text;
                                }}
                            />
                            {errorText && <Text style={[styles.errorText]}>{errorText}</Text>}


                            <View style={[StyleUtils.rowDirection, {alignSelf: 'flex-end', marginTop: 30}]}>
                                <TouchableOpacity onPress={() => {
                                    this.props.success && this.props.success();
                                }} style={[{padding: 8, marginRight: 16}]}>
                                    <Text>{I18n.t('default.cancel')}</Text>
                                </TouchableOpacity>

                                {<TouchableOpacity
                                    onPress={() => {
                                        if (loading)
                                            return;
                                        this.checkUser();
                                    }}
                                    style={[styles.submitBtn, loading && {borderRadius: 100}]}>
                                    {loading ? <ActivityIndicator
                                        size={'small'}
                                        color={'white'}
                                    /> : <Text style={[{color: 'white',}]}>{'Submit'}</Text>
                                    }
                                </TouchableOpacity>}

                            </View>
                        </View>
                    </View>
                </KeyboardAwareScrollView>
            </Modal>
        )
    }
}
const styles = StyleSheet.create({
    box: {
        flex: 1,
        height: height,
        alignItems: 'center',
        justifyContent: 'center',
    },

    alert: {
        backgroundColor: 'white',
        width: '80%',
        padding: 20,
        borderRadius: 10,
    },
    errorText: {
        color: 'red',
        fontSize: 12,
        paddingTop: 6,
    },
    title: {
        fontSize: 18,
        paddingBottom: 8,
        fontWeight: 'bold',
    },
    submitBtn: {
        backgroundColor: 'black',
        padding: 8,
        borderRadius: 4,
    }
});
